package com.cordershy.service;

import com.cordershy.pojo.code;
import com.cordershy.pojo.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
//不同的用户一起注册 需要建立不同的线程 以防止验证失败
@Service
public class mailService {
    @Autowired
    JavaMailSenderImpl javaMailSender;
    @Autowired
    userService userService;
    private code userCode = new code();
    public String sendMail(String mailAddress)  {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper ;
        Integer code = (int)((Math.random()*9+1)*100000);
        userCode.setCode(code.toString());
        userCode.setUsername(mailAddress);
        try {
            helper = new MimeMessageHelper(mimeMessage,true);
            helper.setSubject("注册验证码:");
            helper.setText("<h2 >"+code+"</h2>",true);
            helper.setFrom(new InternetAddress("990100823@qq.com","奶呆记账有限公司", "UTF-8"));
            helper.setTo(mailAddress);
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }

        javaMailSender.send(mimeMessage);
        return "success send mail";
    }
    public String confirmCode(String code,String username,String userpassword){
        user user = new user();
        user.setUsername(username);
        user.setUserpassword(userpassword);
        if (code.equals(userCode.getCode())&&username.equals(userCode.getUsername())){
            System.out.println(userService.insert(user));
            return "success";
        }else{
            return "fail";
        }
    }
}
